#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from urllib.parse import urlparse, parse_qs
from typing import List, Dict
from .base import FilterRule

class UrlChangeFilter(FilterRule):
    """过滤微调 URL 修改"""

    def should_filter(self, add_content: str, remove_content: str, hunk_changes: List[Dict]) -> bool:
        """判断是否为链接的小幅修改：同域同路径且扩展名相同，查询和片段等价"""
        add_clean = add_content.lstrip('+- ').strip()
        remove_clean = remove_content.lstrip('+- ').strip()

        try:
            add_url = urlparse(add_clean)
            remove_url = urlparse(remove_clean)

            # 只处理 http / https
            if add_url.scheme not in ('http', 'https') or remove_url.scheme not in ('http', 'https'):
                return False

            # host 小写统一比较
            if add_url.netloc.lower() != remove_url.netloc.lower():
                return False

            # path 去掉尾部 '/' 后比较
            add_path = add_url.path.rstrip('/')
            remove_path = remove_url.path.rstrip('/')
            if add_path != remove_path:
                return False

            # 查询参数忽略顺序
            def parse_query(q: str) -> Dict[str, List[str]]:
                return {k: sorted(v) for k, v in parse_qs(q, keep_blank_values=True).items()}

            if parse_query(add_url.query) != parse_query(remove_url.query):
                return False

            # 片段必须相同
            if add_url.fragment != remove_url.fragment:
                return False

            # 如果到这里，认为只是微调，可过滤
            return True

        except (ValueError, TypeError) as e:
            # print(f"URL parse error: {e}")
            return False

    def get_filter_reason(self) -> str:
        return "url_change"
